<template>
  <div>
    <BasicTable
      @register="registerTable"
      :can-resize="true"
      :bordered="true"
      :striped="false"
      :data-source="DutyTeamData.teams"
    >
      <template #toolbar>
        <a-button type="primary" @click="onAddDutyTeam"> 新增 </a-button>
      </template>

      <template #action="{ record }">
        <TableAction
          :actions="[
            {
              icon: 'clarity:note-edit-line',
              label: '编辑',
              onClick: onEditDutyTeam.bind(null, record),
            },
            {
              icon: 'ant-design:delete-outlined',
              label: '删除',
              color: 'error',
              popConfirm: {
                title: '是否确认删除',
                confirm: onDeleteDutyTeam.bind(null, record),
              },
            },
            {
              icon: 'ant-design:audit-outlined',
              label: '成员管理',
              color: 'warning',
              onClick: onMembersTable.bind(null, record),
            },
          ]"
        />
      </template>
    </BasicTable>

    <addOrUpdateDutyTeam @register="registerAddOrUpdateForm" @success="afterSuccess" />
    <dutyTeamMembersTable @register="registerMembersTable" @success="afterSuccess" />
  </div>
</template>
<script lang="ts">
  import { defineComponent, ref, reactive, provide, onBeforeMount, onUnmounted } from 'vue';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';

  import { OperationTypeEnum } from '/@/enums/appEnum';
  import { useMessage } from '/@/hooks/web/useMessage';

  import { getAllDutyTeam, deleteDutyTeam } from '/@/api/duty/dutyteam';
  import { dutyTeamTableColumns } from './dutyteam.data';

  //引入子组件
  import addOrUpdateDutyTeam from './AddOrUpdateDutyTeam.vue';
  import dutyTeamMembersTable from './DutyTeamMembersTable.vue';

  //使用modal弹出窗口
  import { useModal } from '/@/components/Modal';
  const { createMessage } = useMessage();

  const [registerAddOrUpdateForm, { openModal: openAddOrUpdateForm }] = useModal();
  const [registerMembersTable, { openModal: openMembersTable }] = useModal();

  export default defineComponent({
    name: 'DutyTeamManagement',
    components: { BasicTable, TableAction, addOrUpdateDutyTeam, dutyTeamMembersTable },
    setup() {
      //定义模块的名称，提供给子孙组件获取使用
      const moduleName = ref('班值管理');
      provide('moduleName', moduleName);

      //处理过后的table数据
      const DutyTeamData = reactive({
        teams: [],
      });

      onBeforeMount(() => {
        console.log('DOM即将挂载');
        getQueryTeamData();
      });
      onUnmounted(() => {
        console.log('销毁完毕');
      });

      /**
       * 请求后台查询接口返回数据显示
       */
      const [registerTable] = useTable({
        title: '班值管理',
        // api: getAllDutyTeam,
        columns: dutyTeamTableColumns, //表头数据
        showTableSetting: true, //是否显示表格设置
        showIndexColumn: true,
        actionColumn: {
          width: 120,
          title: '操作',
          dataIndex: 'action',
          slots: { customRender: 'action' },
          fixed: 'right', //表格操作列是否固定，不设置时默认固定在右侧
        },
        pagination: false, //关闭分页
      });

      /**
       * 查询处理班值信息
       */
      async function getQueryTeamData() {
        if (DutyTeamData.teams.length > 0) {
          DutyTeamData.teams = [];
        }
        getAllDutyTeam()
          .then((res) => {
            console.log('res', res);
            if (res != null) {
              //处理返回数据
              if (res != null) {
                res.forEach((team) => {
                  let result = {
                    id: team.id,
                    groupid: team.groupid,
                    name: team.name,
                    groupname: team.groupname,
                    membersName: '',
                    deptid: team.deptid,
                  };
                  //处理成员列显示格式
                  if (team.members != null && team.members.length > 0) {
                    let members = team.members;
                    let nameStr = '';
                    members.forEach((teamMember) => {
                      if (teamMember.member != null) {
                        nameStr += teamMember.member.name + '，';
                      }
                    });
                    let index = nameStr.lastIndexOf('，');
                    result.membersName = nameStr.substring(0, index);
                  }
                  DutyTeamData.teams.push(result);
                });
              }
            }
            console.log('DutyTeamData', DutyTeamData);
          })
          .catch((ex) => {
            console.log('catch ', ex);
            createMessage.error(ex.msg);
          });
      }

      /**
       * 打开班值新增窗口
       */
      function onAddDutyTeam() {
        //使用props传递数据至子组件，在data参数中指定
        openAddOrUpdateForm(true, { op: OperationTypeEnum.ADD });
      }

      /**
       * 打开班值编辑窗口
       */
      function onEditDutyTeam(record: Recordable) {
        openAddOrUpdateForm(true, { op: OperationTypeEnum.EDIT, dataId: record.id });
      }

      /**
       * 打开班值成员管理弹窗
       */
      function onMembersTable(record: Recordable) {
        openMembersTable(true, {
          op: '成员管理',
          dataId: record.id,
          dutyTeamName: record.name,
          deptid: record.deptid, //分组所属部门
        });
      }

      /**
       * 删除班值
       */
      function onDeleteDutyTeam(record: Recordable) {
        deleteDutyTeam(record.id)
          .then((res) => {
            console.log('res', res);
            //res判断结果：同时==undefined和null
            if (res == undefined && (res == null || Object.keys(res).length == 0)) {
              createMessage.success('删除成功。', 2);
              getQueryTeamData();
            }
          })
          .catch((ex) => {
            console.log('catch ', ex);
            createMessage.error(ex.msg);
          });
      }

      /**
       * 弹窗确认操作之后刷新页面
       */
      function afterSuccess() {
        getQueryTeamData();
      }

      return {
        moduleName,
        registerTable,
        afterSuccess,
        registerAddOrUpdateForm,
        registerMembersTable,

        onAddDutyTeam,
        onEditDutyTeam,
        onDeleteDutyTeam,
        onMembersTable,

        DutyTeamData,
        getQueryTeamData,
      };
    },
  });
</script>
